package lock;

/**
 * 死锁案例
 *
 * @author codefish
 * @version 1.0
 * @date 2022/08/05 上午 10:59
 */
public class DeadLockDemo {
    static final Object obj1 = new Object();
    static final Object obj2 = new Object();

    public static void main(String[] args) {
        new Thread(() -> {
            //循环请求资源100次，增加死锁发生概率
            for (int i = 0; i < 100; i++) {
                System.out.println(threadTag() + "等待获取资源A");
                synchronized (obj1) {
                    System.out.println(threadTag() + "获取资源A，等待获取资源B");
                    synchronized (obj2) {
                        System.out.println(threadTag() + "获取资源B");
                    }
                }
            }
        }, "t1").start();
        new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                System.out.println(threadTag() + "等待获取资源B");
                synchronized (obj2) {
                    System.out.println(threadTag() + "获取资源B，等待获取资源A");
                    synchronized (obj1) {
                        System.out.println(threadTag() + "获取资源A");
                    }
                }
            }
        }, "t2").start();
    }

    public static String threadTag() {
        return "[" + Thread.currentThread().getName() + "]";
    }


}
